﻿using System.Net.Sockets;
using System.Net;
using System.Text;

namespace TcpServerRelayTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //IPAddress.Any为所有网卡，
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 6001);
            //创建listens是传入的套接字。
            Socket listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.NoDelay = true;
            //绑定端口
            listenSocket.Bind(localEndPoint);
            //挂起的连接队列的最大长度。
            listenSocket.Listen(1000);
            Console.WriteLine("Server Accept...");
            Socket clientSocket = listenSocket.Accept();
            Console.WriteLine("连接上的设备信息：{0}",clientSocket.RemoteEndPoint);
            int count = 0;
            while (true)
            {
                string cmd = "AT+STACH1=1\r\n";
                try {
                    Console.WriteLine("发送吸合指令:{0}", cmd);
                    byte[] bytes = Encoding.ASCII.GetBytes(cmd);
                    clientSocket.Send(bytes);
                    Thread.Sleep(1000);

                    cmd = "AT+STACH1=0\r\n";
                    Console.WriteLine("发送断开指令:{0}", cmd);
                    bytes = Encoding.ASCII.GetBytes(cmd);
                    clientSocket.Send(bytes);
                    Thread.Sleep(1000);
                } catch (SocketException e) {
                    Console.WriteLine(e.ToString());
                    clientSocket.Close();
                    clientSocket = listenSocket.Accept();
                    Console.WriteLine("连接上的设备信息：{0}", clientSocket.RemoteEndPoint);
                }

                count ++;
                if(count == 500) {
                    break;                
                }
            }
            clientSocket.Close();
            listenSocket.Close();
        }
    }
}